﻿
/*  
    Copyright (C) <2007-2013>  <Kay Diefenthal>

    DD.UI.MediaCenter is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DD.UI.MediaCenter is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DD.UI.MediaCenter.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using DD.UI.MediaCenter.Logging;
using DD.UI.MediaCenter.ObjectModels;
using DD.UI.MediaCenter.Views;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;

namespace DD.UI.MediaCenter.ViewModels
{
    public class DefaultViewModel : ModelItem
    {
        #region Private Fields

        private readonly Timer _delayTimer;
        private readonly AddInHost _host;
        private readonly HistoryOrientedPageSession _session;
        private Station _station;

        #endregion

        #region Constructor

        public DefaultViewModel(HistoryOrientedPageSession session, AddInHost host)
        {
            _session = session;
            _host = host;
            _station = null;
            var timer = new Timer {Enabled = true, Interval = 0xbb8, AutoRepeat = false};
            _delayTimer = timer;
            _delayTimer.Tick += OnDelayTimerTick;
        }

        #endregion

        #region Properties

        public MediaCenterEnvironment MediaCenterEnvironment
        {
            get
            {
                if (_host == null)
                {
                    return null;
                }
                return _host.MediaCenterEnvironment;
            }
        }

        #endregion

        #region Private Methods

        private DefaultView CreateDefaultView()
        {
            var view = new DefaultView();
            RetrieveStations(view);
            return view;
        }

        private void GoToEndOfStream()
        {
            MediaCenterEnvironment.MediaExperience.Transport.Position = TimeSpan.MaxValue;
        }

        private bool IsPlaying()
        {
            if (MediaCenterEnvironment.MediaExperience == null)
            {
                return false;
            }
            if (((MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Stopped) | (MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Finished)) | (MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Undefined))
            {
                return false;
            }
            return true;
        }

        private void OnDelayTimerTick(object sender, EventArgs e)
        {
            if (IsPlaying())
            {
                StopPlaying();
                StartStream();
            }
            StartStream();
        }

        private void Play(string media)
        {
            MediaCenterEnvironment.PlayMedia(MediaType.Video, media, false);
        }

        private void RetrieveInformations(DefaultView view, Station station)
        {
            try
            {
                _station = station;
                view.Informations = station.ServiceName;
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("{0}{1}{2}", "DefaultViewModel", "RetrieveInformations",exception));
            }
        }

        private void RetrieveStations(DefaultView view)
        {
            EventHandler handler = null;
            try
            {
                var options = new ArrayListDataSet(view);
                var source = Utils.GetStationsFromLocalFile_m3u(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Digital Devices\PlayLists\Channels.m3u");
                options.CopyFrom(source);
                var choice2 = new Choice(view, null, options) {Chosen = options[1]};
                var choice = choice2;
               _station = (Station) options[1];
                view.Channels = choice;
                if (options.Count > 0)
                {
                    if (handler == null)
                    {
                        handler = delegate (object sender, EventArgs e) {
                            var defaultview = (DefaultView) sender;
                            var station = (Station)defaultview.Channels.Chosen;
                            RetrieveInformations(defaultview, station);
                            _delayTimer.Stop();
                            _delayTimer.Start();
                        };
                    }
                    view.ChannelChanged += handler;
                }
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("{0}{1}{2}", "DefaultViewModel", "RetrieveStations", exception));
            }
        }

        private void StartStream()
        {
            if ((_station != null) && !string.IsNullOrEmpty(_station.ServiceStream))
            {
                Play(_station.ServiceStream);
            }
        }

        private void StopPlaying()
        {
            MediaCenterEnvironment.MediaExperience.Transport.PlayRate = 0f;
        }

        #endregion

        #region Public Methods

        public void GoToDefaultView()
        {
            var uiProperties = new Dictionary<string, object>();
            uiProperties["DefaultView"] = CreateDefaultView();
            _session.GoToPage("resx://DD.UI.MediaCenter/DD.UI.MediaCenter.Resources/DefaultView", uiProperties);
        }
        #endregion
    }
}




